from __future__ import absolute_import

import md5
from . import token
from scopt.util import message as msg_util
from scopt.util.message_types import STRING


@token(version='0.1',
       token={'type': 'security.flyby.login.password',
              'login': STRING(required=True),
              'password': STRING(required=True)})
def handle(data_packet, registry):
    security_token = msg_util.get_security_token(data_packet)
    login = security_token['login']
    md5pwd = md5.new(security_token['password']).hexdigest()
    result = registry.query('users',
                            where=[['users.login', login],
                                   ['users.md5pwd', md5pwd]])
    if len(result) == 0:
        return msg_util.exception(data_packet,
                                  'security.invalid.login.password')
    user = result[0]
    login = 'ADMIN' if user['admin'] else user['login']
    data_packet['security'] = {'principal': {'login': login,
                                             'username': user['username']}}
    return data_packet
